package com.billionsfinance.hessian.core;

import com.billionsfinance.hessian.model.ClientInfo;
import com.caucho.hessian.client.HessianProxyFactory;

import java.net.MalformedURLException;

/**
 * 获取远程Hessian对象
 *
 * @ClassName: RemoteCall
 * @author: WeiHui.Zhang
 * @date: 2016/11/7 19:07
 * @version: v1.0.0
 */
public class RemoteCall {

	/**
	 * 获取远程对象
	 *
	 * @param classType
	 * @param connTimeout
	 * @param readTimeout
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getRemoteObject(Class<T> classType, int connTimeout, int readTimeout) {
		ClientInfo clientInfo = HessianCacheManager.getClientInfo(classType.getName());
		if (clientInfo == null) {
			throw new RuntimeException(
					"Interface [" + classType.getName() + "] is not registered in the client table!");
		}
		String url = clientInfo.getAccessUrl();
		String interfaceName = clientInfo.getInterfaceName();
		HessianProxyFactory factory = new HessianProxyFactory();
		if (readTimeout > 0) {
			factory.setReadTimeout(readTimeout * 1000);
		} else {
			factory.setReadTimeout(clientInfo.getReadTimeout() * 1000);
		}
		if (connTimeout > 0) {
			factory.setConnectTimeout(readTimeout * 1000);
		} else {
			factory.setConnectTimeout(clientInfo.getReadTimeout() * 1000);
		}
		T object = null;
		Class<?> interfaceClass = HessianCacheManager.getHessianClientInterfaceClass(interfaceName);
		try {
			object = (T) factory.create(interfaceClass, url);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		return object;
	}

	/**
	 * 获取远程Hessian对象
	 *
	 * @param classType 接口类
	 * @return 接口类
	 */
	public static <T> T getRemoteObject(Class<T> classType) {
		return getRemoteObject(classType, 0, 0);
	}

}